package cn.com.dashihui.web.controller;

import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.common.CacheHolder;
import cn.com.dashihui.web.dao.AdminSeller;
import cn.com.dashihui.web.dao.Resource;
import cn.com.dashihui.web.service.AdminService;
import cn.com.dashihui.web.service.ResourceService;
import cn.com.dashihui.web.service.SellerService;

public class SystemController extends BaseController {
	private ResourceService resourceService = new ResourceService();
	private AdminService adminService = Duang.duang(AdminService.class);
	private SellerService sellerService = Duang.duang(SellerService.class);

	/**
	 * 跳转登录页
	 */
	public void login() {
		this.render("login.jsp");
	}
	/**
	 * 跳转住框架页
	 */
	public void main() {
		if (getCurrentUser()==null) {
			render("login.jsp");
		}else {
			render("main.jsp");
		}
		
	}
	@RequiresAuthentication
	public void index() {
		// 获取当前登录用户的id
		int userid = getCurrentUser().getInt("id");
		logger.info("getCurrentUser()>>"+getCurrentUser());
		logger.info("userId>>"+userid);
		int RoleId = sellerService.findByRoleId(userid);
		if (RoleId == 1) {
			//查询总普通订单销售额
			Record recor = sellerService.countNumberAdmin();
			//查询总团购订单销售额
			Record recorgb = sellerService.countNumberAdmingb();
			int orderNum1 = recor.getInt("orderNum");
			int orderNumgb = recorgb.getInt("orderNum");
			setAttr("orderNum", orderNum1);
			setAttr("orderNumgb", orderNumgb);
			double amount1 = recor.getDouble("amount");
			double amountgb = recorgb.getDouble("amount");
			setAttr("amount", amount1);
			setAttr("amountgb", amountgb);
			render("index.jsp");
		} else if (RoleId == 2) {
			// 查询当前用户的是否已经注册过sellerid
			Record record = sellerService.FindById(userid);
			if (record == null || record.getInt("state")!=2){
				String selleridd = "SE" + userid + CommonKit.buildRandomString();
				setAttr("sellerid", selleridd);
				redirect("/dict/seller/index");
			} else {
				String sellerId = null;
				if (StrKit.notNull(sellerService.findByUserId(userid))) {
					sellerId = sellerService.findByUserId(userid).get("sellerId");
				}
				Record recor = sellerService.countNumber(sellerId);
				if (recor!=null) {
					Record recorgb = sellerService.countNumbergb(sellerId);
					int orderNum1 = recor.getInt("orderNum");
					setAttr("orderNum", orderNum1);
					int orderNumgb = recorgb.getInt("orderNum");
					setAttr("orderNumgb", orderNumgb);
					double amount1 = recor.getDouble("amount");
					setAttr("amount", amount1);
					double amountgb = recorgb.getDouble("amount");
					setAttr("amountgb", amountgb);
				}else{
					redirect("/bus/goods/base/index");
				}
				render("index.jsp");
			}
		} else {
			if (StrKit.notNull(sellerService.findStoreState(userid))){
				
				String storeid = sellerService.findStoreState(userid).get("storeid");
				Record recor = sellerService.countstoreidNumber(storeid);
				Record recorgb = sellerService.countstoreidNumbergb(storeid);
				int orderNum1 = recor.getInt("orderNum");
				int orderNumgb = recorgb.getInt("orderNum");
				setAttr("orderNum", orderNum1);
				setAttr("orderNumgb", orderNumgb);
				double amount1 = recor.getDouble("amount");
				double amountgb = recorgb.getDouble("amount");
				setAttr("amount", amount1);
				setAttr("amountgb", amountgb);
				render("index.jsp");
			}
		}

	}

	/**
	 * 分页首页
	 */
	public void page() {
		int userid = getCurrentUser().getInt("id");
		int RoleId = sellerService.findByRoleId(userid);
		String storeid = null;
		String sellerId = null;
		if(RoleId == 1){
			
		}else if (RoleId == 2) {
			if(StrKit.notBlank(adminService.findBysellerId(userid))){
				sellerId = adminService.findBysellerId(userid);
			}
		} else{
			if (StrKit.notBlank(adminService.findByStoreid(userid))) {
				storeid = adminService.findByStoreid(userid);
				sellerId = adminService.findBysellerId(storeid).get("sellerId");
			}
		}
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		System.out.println(sellerId+storeid);
		renderResult(0, sellerService.findByTotle(RoleId, pageNum, pageSize, sellerId, storeid));
	}



	/**
	 * 登录操作
	 * 
	 * @return 1：用户名为空，2：密码为空，3：用户名或密码错误，4：网络繁忙...
	 */
	public void doLogin() {
		try {
			String username = getPara("username");
			String password = getPara("password");
			if (StrKit.isBlank(username)) {
				// 用户名为空
				this.renderResult(1);
			} else if (StrKit.isBlank(password)) {
				// 密码为空
				this.renderResult(2);
			} else {
				// 根据入参创建token
				boolean rememberMe = getParaToBoolean("rememberMe", false);
				String host = getRequest().getRemoteHost();
				UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, password, rememberMe,
						host);
				// 认证
				Subject currentUser = SecurityUtils.getSubject();
				currentUser.login(authenticationToken);
				AdminSeller currUser = (AdminSeller) currentUser.getPrincipal();
				int roleid = adminService.findRoleIdByUserid(currUser.getInt("id"));
				//如果是公司登陆
				if (roleid==2) {
					logger.info(">>>>>>>>>>>>"+currUser.getInt("id"));
					Record record = adminService.findByUserid(currUser.getInt("id"));
					logger.info("record>>>>>>>>>>>>"+record);
					if (record==null){
						List<Resource> navM = resourceService.findMenu();
						this.setSessionAttr(CacheHolder.NAVMENUS, navM);
						this.renderSuccess();
						return;
					} 
					if (record!=null&&record.getInt("state")!=2) {
						List<Resource> navM = resourceService.findMenu();
						this.setSessionAttr(CacheHolder.NAVMENUS, navM);
						this.renderSuccess();
						return;
					}
				} 
				// 查询登录用户可操作的菜单
				List<Resource> navMenus = resourceService.findMenuResourcesByUser(currUser.getInt("id"));
				this.setSessionAttr(CacheHolder.NAVMENUS, navMenus);
				//页面按钮权限
				Map<String,String> popedomMap = resourceService.queryPopedom(currUser.getInt("id"));
				this.setSessionAttr("userpopedom", popedomMap);
				/*//菜单权限--拆分整理成嵌套形式的集合
				Map<String,String> popedom = new Hashtable<String,String>();
				Map<String,String> caidan = new Hashtable<String,String>();
				Map<String,String> page = new Hashtable<String,String>();
				
				for(Resource resource : navMenus){
					//菜单权限
					caidan.put(resource.getStr("code"), "1");
					List<Resource> pageResource = resource.getChildren();
					for(Resource pageRs : pageResource){
						//页面权限
						page.put(pageRs.getStr("code"), "1");
						List<Resource> buttoneResource = pageRs.getChildren();
						if(buttoneResource!=null){
							for(Resource button : buttoneResource){
								//按钮权限
								popedom.put(button.getStr("code"), "1");
							}
						}
					};
				}
				System.out.println(caidan);
				System.out.println("------------------"+currUser.getInt("id")+"---------------------");
				System.out.println(popedom);*/
				
				logger.info("currUser>>>>"+currUser);
				// 登录成功
				this.renderSuccess();
			}
		} catch (AuthenticationException e) {
			// e.printStackTrace();
			logger.error("登录失败");
			// 用户名或者密码错误
			this.renderResult(3);
		} catch (Exception e) {
			e.printStackTrace();
			// 网络繁忙...
			this.renderResult(4);
		}
	}

	public void toEditMinePwd() {
		render("editMinePwd.jsp");
	}

	/**
	 * 更新当前登录用户的密码
	 * 
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	public void doEditMinePwd() {
		// 原密码
		String passwordOld = getPara("passwordOld");
		// 新设密码
		String passwordNew = getPara("passwordNew");
		if (StrKit.isBlank(passwordOld)) {
			renderResult(1);
			return;
		} else if (StrKit.isBlank(passwordNew)) {
			renderResult(2);
			return;
		} else if (passwordNew.length() > 100) {
			renderResult(3);
			return;
		} else {
			// 更新
			try {
				if (adminService.editMinePwd(getCurrentUser(), passwordOld, passwordNew)) {
					renderSuccess();
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
				// 原密码输入错误
				renderResult(4);
				return;
			}
		}
		renderFailed();
	}

	public void logout() {
		Subject currentUser = SecurityUtils.getSubject();
		try {
			if (currentUser.isAuthenticated())
				currentUser.logout();
			this.redirect("/login");
		} catch (SessionException ise) {
			logger.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
		} catch (Exception e) {
			logger.debug("登出发生错误", e);
		}
	}

	public void error401() {
		render("401.jsp");
	}

	public void error403() {

		render("403.jsp");
	}

	public void error404() {
		render("404.jsp");
	}

	public void error500() {
		render("500.jsp");
	}
}
